package ui;

import dao.HouseInfoDao;
import entity.HouseEntity;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;

public class HouseInfoManagementGUI extends JFrame {
    //public static void main(String[] args) throws Exception {
    public void showa() throws Exception{
        JFrame frame = new JFrame("房屋信息管理");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);

        // 创建顶部面板
        JPanel topPanel = new JPanel();
        JLabel addressLabel = new JLabel("地址:");
        JTextField addressField = new JTextField(20);
        JLabel priceLabel = new JLabel("价格:");
        JTextField priceField = new JTextField(10);
        JButton queryButton = new JButton("查询");
        JButton deleteButton = new JButton("删除");
        topPanel.add(addressLabel);
        topPanel.add(addressField);
        topPanel.add(priceLabel);
        topPanel.add(priceField);
        topPanel.add(queryButton);
        topPanel.add(deleteButton);

        // 创建中间的列表框
        String[] columnNames = {"id","地址", "价格", "面积", "发布时间", "发布人", "备注"};
        Object[][] data = updateList(null,null);
        DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
        JTable table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);

        // 创建底部的展示框
        JPanel bottomPanel = new JPanel();
        JLabel displayAddressLabel = new JLabel("地址:");
        JTextField displayAddressField = new JTextField(30);
        JLabel displayPriceLabel = new JLabel("价格:");
        JTextField displayPriceField = new JTextField(30);
        JLabel displayAreaLabel = new JLabel("面积:");
        JTextField displayAreaField = new JTextField(30);
        JLabel displayPublishTimeLabel = new JLabel("发布时间:");
        JTextField displayPublishTimeField = new JTextField(30);
        JLabel displayPublishUserLabel = new JLabel("发布人:");
        JTextField displayPublishUserField = new JTextField(30);
        JLabel displayRemarksLabel = new JLabel("备注:");
        JTextField displayRemarksField = new JTextField(30);
        JButton updateButton = new JButton("更新");
        JButton addButton = new JButton("新增");
        bottomPanel.setLayout(new GridLayout(7, 1));
        bottomPanel.add(displayAddressLabel);
        bottomPanel.add(displayAddressField);
        bottomPanel.add(displayPriceLabel);
        bottomPanel.add(displayPriceField);
        bottomPanel.add(displayAreaLabel);
        bottomPanel.add(displayAreaField);
        bottomPanel.add(displayPublishTimeLabel);
        bottomPanel.add(displayPublishTimeField);
        bottomPanel.add(displayPublishUserLabel);
        bottomPanel.add(displayPublishUserField);
        bottomPanel.add(displayRemarksLabel);
        bottomPanel.add(displayRemarksField);
        bottomPanel.add(updateButton);
        bottomPanel.add(addButton);

        // 将组件添加到 JFrame
        frame.add(topPanel, BorderLayout.NORTH);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.add(bottomPanel, BorderLayout.SOUTH);

        // 监听表格事件
        table.getSelectionModel().addListSelectionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                String selectedAddress = table.getValueAt(selectedRow, 1).toString();
                String selectedPrice = table.getValueAt(selectedRow, 2).toString();
                String selectedArea = table.getValueAt(selectedRow, 3).toString();
                String publishTime = table.getValueAt(selectedRow, 4).toString();
                String publishUser = table.getValueAt(selectedRow, 5).toString();
                String selectedRemarks = table.getValueAt(selectedRow, 6).toString();

                displayAddressField.setText(selectedAddress);
                displayPriceField.setText(selectedPrice);
                displayAreaField.setText(selectedArea);
                displayPublishTimeField.setText(publishTime);
                displayPublishUserField.setText(publishUser);
                displayRemarksField.setText(selectedRemarks);
            }
        });

        // 监听查询按钮点击事件
        queryButton.addActionListener(e -> {
            String address = addressField.getText();
            Integer price = null;
            if(priceField.getText()!=null&&!priceField.getText().equals("")){
                price = Integer.parseInt(priceField.getText());
            }
            Object[][] newdata = new Object[0][];
            try {
                newdata = updateList(address, price);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            tableModel.setDataVector(newdata, columnNames);
        });

        // 监听删除按钮点击事件
        deleteButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                String address = addressField.getText();
                Integer price = null;
                if(priceField.getText()!=null&&!priceField.getText().equals("")){
                    price = Integer.parseInt(priceField.getText());
                }
                int rowId = Integer.parseInt(table.getValueAt(selectedRow, 0).toString());
                Object[][] newdata = new Object[0][];
                try {
                    newdata = deleteList(rowId,address, price);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
                tableModel.setDataVector(newdata, columnNames);
                JOptionPane.showMessageDialog(frame, "信息已删除");
            } else {
                JOptionPane.showMessageDialog(frame, "请先选择一个房源");
            }
        });

        // 监听更新按钮点击事件
        updateButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                int id = Integer.parseInt(table.getValueAt(selectedRow, 0).toString());
                String address = displayAddressField.getText();
                Integer price = Integer.parseInt(displayPriceField.getText());
                Integer area = Integer.parseInt(displayAreaField.getText());
                String publishTime = displayPublishTimeField.getText();
                String publishUser = displayPublishUserField.getText();
                String remark = displayRemarksField.getText();
                HouseEntity entity = new HouseEntity();
                entity.setId(id);
                entity.setAddress(address);
                entity.setPrice(price);
                entity.setArea(area);
                entity.setPublishTime(publishTime);
                entity.setPublishUser(publishUser);
                entity.setRemark(remark);
                String queryaddress = addressField.getText();
                Integer queryPrice = null;
                if(priceField.getText()!=null&&!priceField.getText().equals("")){
                    queryPrice = Integer.parseInt(priceField.getText());
                }

                Object[][] newdata = new Object[0][];
                try {
                    newdata = updateHouse(entity,queryaddress, queryPrice);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
                tableModel.setDataVector(newdata, columnNames);
                JOptionPane.showMessageDialog(frame, "信息已更新");
            } else {
                JOptionPane.showMessageDialog(frame, "请先选择一个房源");
            }
        });

        // 监听新增按钮点击事件
        addButton.addActionListener(e -> {
            String addAddress = displayAddressField.getText();
            String addPrice = displayPriceField.getText();
            String addArea = displayAreaField.getText();
            String addPublishTime = displayPublishTimeField.getText();
            String addPublishUser = displayPublishUserField.getText();
            String addRemark = displayRemarksField.getText();

            String address = addressField.getText();
            Integer price = null;
            if(priceField.getText()!=null&&!priceField.getText().equals("")){
                price = Integer.parseInt(priceField.getText());
            }

            Object[][] newdata = new Object[0][];
            try {
                newdata = addList(addAddress,Integer.parseInt(addPrice),Integer.parseInt(addArea),
                        addPublishTime,addPublishUser,addRemark,address,price);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            tableModel.setDataVector(newdata, columnNames);
            JOptionPane.showMessageDialog(frame, "信息已新增");
        });



        frame.setVisible(true);
    }

    private static Object[][] updateList(String address, Integer price) throws Exception {
        HouseInfoDao dao = new HouseInfoDao();
        List<HouseEntity> houseEntities = dao.fetchData(address, price);
        Object[][] data = new Object[houseEntities.size()][7];
        for (int i = 0; i < houseEntities.size(); i++) {
            HouseEntity houseEntity = houseEntities.get(i);
            data[i][0] = houseEntity.getId();
            data[i][1] = houseEntity.getAddress();
            data[i][2] = houseEntity.getPrice();
            data[i][3] = houseEntity.getArea();
            data[i][4] = houseEntity.getPublishTime();
            data[i][5] = houseEntity.getPublishUser();
            data[i][6] = houseEntity.getRemark();
        }
        return data;
    }

    private static Object[][] deleteList(int rowId,String address,Integer price) throws Exception {
        HouseInfoDao dao = new HouseInfoDao();
        dao.deleteData(rowId);
        List<HouseEntity> houseEntities = dao.fetchData(address, price);
        Object[][] data = new Object[houseEntities.size()][7];
        for (int i = 0; i < houseEntities.size(); i++) {
            HouseEntity houseEntity = houseEntities.get(i);
            data[i][0] = houseEntity.getId();
            data[i][1] = houseEntity.getAddress();
            data[i][2] = houseEntity.getPrice();
            data[i][3] = houseEntity.getArea();
            data[i][4] = houseEntity.getPublishTime();
            data[i][5] = houseEntity.getPublishUser();
            data[i][6] = houseEntity.getRemark();
        }
        return data;
    }

    private static Object[][] addList(String address,
                                      Integer price,
                                      Integer area,
                                      String publishTime,
                                      String publishUser,
                                      String remark,
                                      String queryAddress,
                                      Integer queryPrice) throws Exception {
        HouseInfoDao dao = new HouseInfoDao();
        dao.insertData(address,price,area,publishTime,publishUser,remark);
        List<HouseEntity> houseEntities = dao.fetchData(queryAddress, queryPrice);
        Object[][] data = new Object[houseEntities.size()][7];
        for (int i = 0; i < houseEntities.size(); i++) {
            HouseEntity houseEntity = houseEntities.get(i);
            data[i][0] = houseEntity.getId();
            data[i][1] = houseEntity.getAddress();
            data[i][2] = houseEntity.getPrice();
            data[i][3] = houseEntity.getArea();
            data[i][4] = houseEntity.getPublishTime();
            data[i][5] = houseEntity.getPublishUser();
            data[i][6] = houseEntity.getRemark();
        }
        return data;
    }

    private static Object[][] updateHouse(HouseEntity house,String address, Integer price) throws Exception {
        HouseInfoDao dao = new HouseInfoDao();
        dao.updateData(house);
        List<HouseEntity> houseEntities = dao.fetchData(address, price);
        Object[][] data = new Object[houseEntities.size()][7];
        for (int i = 0; i < houseEntities.size(); i++) {
            HouseEntity houseEntity = houseEntities.get(i);
            data[i][0] = houseEntity.getId();
            data[i][1] = houseEntity.getAddress();
            data[i][2] = houseEntity.getPrice();
            data[i][3] = houseEntity.getArea();
            data[i][4] = houseEntity.getPublishTime();
            data[i][5] = houseEntity.getPublishUser();
            data[i][6] = houseEntity.getRemark();
        }
        return data;
    }

}
